package com.atguigu.servlet.model;

import com.atguigu.bean.Cart;
import com.atguigu.bean.Order;
import com.atguigu.bean.User;
import com.atguigu.service.OrderService;
import com.atguigu.service.impl.OrederServiceImpl;
import com.atguigu.servlet.base.BaseServlet;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.List;

public class OrderServlet extends BaseServlet {
    private OrderService orderService = new OrederServiceImpl();
    //结账功能
    //order?flag=checkout
    protected void checkout(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //1.取值
        //获取购物车
        HttpSession session = request.getSession();
        Cart cart = (Cart)session.getAttribute("cart");
        //获得用户
        User userlogin = (User)session.getAttribute("userlogin");
        //2.调用业务层创建订单
        /**
         * ①：创建一个Order对象（），通过dao层添加数据
         * ②：创建n个订单（OrderItem），通过dao层添加数据库
         * ③：修改图书的库存和销量
         * ④：购物车清空
         */

       String order=orderService.createOrder(cart,userlogin);
        //3.购物车清空
        session.removeAttribute("cart");
        //4.响应
        request.setAttribute("orderId",order);
        this.processTemplate("cart/checkout",request,response);
    }
    //order?flag=order
    protected void order(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
        //我的订单，根据id来查询我的订单
         User userlogin= (User)request.getSession().getAttribute("userlogin");
        int id= userlogin.getId();
       //2. 去查询当前用户的订单
        List<Order> orderByUserId = orderService.findAllOrderById(id);
        //3. 将list集合存储在请求域
        request.setAttribute("orders",orderByUserId);
        this.processTemplate("order/order",request,response);
    }
}
